package cron;

import java.io.IOException;
import java.io.PrintWriter;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.logging.Logger;
import javax.servlet.ServletException;

import utils.UsersInfo;

import models.Area;
import models.Benefit;
import models.Location;
import models.SolutionSubmission;
import models.SolutionSubscription;
import models.Customer;

import com.google.appengine.api.appidentity.AppIdentityServiceFactory;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

@SuppressWarnings("serial")
public class cronDailyNotificationServlet extends HttpServlet {
	private static final Logger _logger = Logger.getLogger(cronDailyNotificationServlet.class.getName());
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/html");
		PrintWriter out = resp.getWriter();
		
		try{
		boolean found = false;
		// Get today as a Calendar  
		Calendar today = Calendar.getInstance();  
		// Subtract 1 day  
		today.add(Calendar.DATE, -1);  
		// get the yesterday date  
		java.util.Date yesterday = new java.util.Date (today.getTimeInMillis());
		java.util.Date todayDate = new java.util.Date();
		out.println("*Yesterday day: " + yesterday + "<br />");
		out.println("*Today Date: " + todayDate + "<br />");
		//String siteURL = System.getProperty("SITE_URL");
		String siteURL = AppIdentityServiceFactory.getAppIdentityService().getServiceAccountName();
		if( siteURL.indexOf("@") > 0){
			int idex = siteURL.indexOf("@");
			siteURL = siteURL.substring(0, idex-1);
		}
		siteURL = "http://" + siteURL + ".appspot.com";
		
		Long custID;
		Long areaID;
		Long benefitID;
		Long locID;
		String userEmail = "";
		String Subject =  "";
		String MessageBody = "";
		
		String custName = "";
		String areaName = "";
		String benefitName = "";
		String locName = "";
		
		Objectify ofy = ObjectifyService.begin();
		Objectify ofy1 = ObjectifyService.begin();
		Objectify ofy2 = ObjectifyService.begin();
		Query<SolutionSubmission> solItem = ofy.query(SolutionSubmission.class).filter("Status", "Shared").filter("submittedON >=", yesterday).filter("submittedON <=", todayDate);
		Query<SolutionSubscription> q = ofy1.query(SolutionSubscription.class).order("subscribeBY");
		
		List<String> arrCustName = new ArrayList<String>();
		List<String> arrAreaName = new ArrayList<String>();
		List<String> arrBenefitName = new ArrayList<String>();
		List<String> arrLocName = new ArrayList<String>();
		
		List<String> arrhardSavings = new ArrayList<String>();
		List<String> arrcostAvoidance = new ArrayList<String>();
		List<String> arrOpportunityCost = new ArrayList<String>();
		
		List<String> arrSolID = new ArrayList<String>();
		List<String> arrSubmittedBY = new ArrayList<String>();
		
		for (SolutionSubmission ff : solItem.fetch()) {
			arrCustName.add( ff.getCustomer() );
			arrAreaName.add( ff.getProcessArea() );
			arrBenefitName.add( ff.getAchievedTypeDesc() );
			arrLocName.add( ff.getLocation() );
			
			arrhardSavings.add( "" + ff.isHasHardSavings());
			arrcostAvoidance.add( "" + ff.isHasCostAvoidance() );
			arrOpportunityCost.add( "" + ff.isHasOppurtunityCost() );
			
			arrSolID.add( "" + ff.getSolID() );			
			arrSubmittedBY.add( ff.getSubmittedBY() );
		}
		
		userEmail = "";
		String prevUserEmail = "";
		String MessageSubject = "[Ops Central] Notification on the Solution Subscription";
		MessageBody = "";
		found = false;
		boolean firstTime = true;
		
		for (SolutionSubscription f : q.fetch()) {
			userEmail = f.getSubscribeBY();
			
			//FIRST TIME
			if( prevUserEmail.equals("") ){
				prevUserEmail = userEmail;
			}
			
			//IF PREVIOUS DOES NOT MATCHES WITH PRESENT THEN THIS IS NEW USER
			if( !prevUserEmail.equalsIgnoreCase(userEmail) ){
				if( !MessageBody.equals("") ){
					sendEmail(prevUserEmail, "srvan@celestica.com" , MessageSubject, MessageBody, resp);
				}
				
				MessageBody = "";				
			}
			
			custID = f.getCustID(); if (custID == null ){ custID = 0L; }
			areaID = f.getAreaID();	if (areaID == null ){ areaID = 0L; }
			benefitID = f.getBenefitID(); if (benefitID == null ){ benefitID = 0L; }
			locID = f.getLocID(); if (locID == null ){ locID = 0L; }
			
			if( custID > 0 ){	
				Customer custItem = ofy2.get(Customer.class, custID);
				custName = custItem.getCustName();				
				if ( custName != null && !custName.equals("") ){
					firstTime = true;
					for (int i = 0; i < arrSolID.size(); i++) {							
						if( arrCustName.get(i).equalsIgnoreCase(custName) ){
							if( firstTime ){
								MessageBody = MessageBody + "Notification for [Customer]: <b>" + custName + "</b><br /><br />";
							}
							
							MessageBody = MessageBody + "New Solution submitted: " + siteURL + "/modules/default/display-solution.jsp?sol_id=" + arrSolID.get(i) + "<br />";
							firstTime = false;
						}
					}						
				}
			} //custID > 0

			if( areaID > 0 ){	
				Area areaItem = ofy.get(Area.class, areaID);
				areaName = areaItem.getAreaName();
				if ( areaName != null && !areaName.equals("") ){
					firstTime = true;
					for (int i = 0; i < arrSolID.size(); i++) {							
						if( arrAreaName.get(i).equalsIgnoreCase(areaName) ){
							if( firstTime ){
								MessageBody = MessageBody + "Notification for [Process Area]: <b>" + areaName + "</b><br /><br />";
							}
							
							MessageBody = MessageBody + "New Solution submitted: " + siteURL + "/modules/default/display-solution.jsp?sol_id=" + arrSolID.get(i) + "<br />";
							firstTime = false;
						}
					}						
				}
			}//areaID
			
			if( benefitID > 0 ){	
				Benefit benefitItem = ofy.get(Benefit.class, benefitID);
				benefitName = benefitItem.getBenefitName();
				if ( benefitName != null && !benefitName.equals("") ){
					firstTime = true;
					for (int i = 0; i < arrSolID.size(); i++) {							
						if( arrBenefitName.get(i).equalsIgnoreCase(benefitName) || arrhardSavings.get(i).equalsIgnoreCase("true") || 
								arrcostAvoidance.get(i).equalsIgnoreCase("true") || arrOpportunityCost.get(i).equalsIgnoreCase("true") ){
							if( firstTime ){
								MessageBody = MessageBody + "Notification for [Benefits]: <b>" + benefitName + "</b><br /><br />";
							}
							
							MessageBody = MessageBody + "New Solution submitted: " + siteURL + "/modules/default/display-solution.jsp?sol_id=" + arrSolID.get(i) + "<br />";
							firstTime = false;
						}
					}						
				}
			}//benefitID
			
			if( locID > 0 ){	
				Location locItem = ofy.get(Location.class, locID);
				locName = locItem.getLocationName();
				if ( locName != null && !locName.equals("") ){
					firstTime = true;
					for (int i = 0; i < arrSolID.size(); i++) {							
						if( arrLocName.get(i).equalsIgnoreCase(locName) ){							
							if( firstTime ){
								MessageBody = MessageBody + "Notification for [Location]: <b>" + locName + "</b><br /><br />";
							}
							
							MessageBody = MessageBody + "New Solution submitted: " + siteURL + "/modules/default/display-solution.jsp?sol_id=" + arrSolID.get(i) + "<br />";
							firstTime = false;
						}
					}						
				}
			}//locID
			
			
			//SAVE THE PREVIOUS EMAIL ID
			prevUserEmail = userEmail;
			found = true;
		}
		
		//LAST ORPHAN MESSAGE
		if( found && !MessageBody.equals("") ){
			sendEmail(userEmail, "srvan@celestica.com" , MessageSubject, MessageBody, resp);
		}
		
		/*
		for (SolutionSubmission ff : solItem.fetch()) {
			
			for (SolutionSubscription f : q.fetch()) {

				custID = areaID = benefitID = locID = 0L;
				
				custID = f.getCustID();
				if (custID == null ){
					custID = 0L;
				}

				areaID = f.getAreaID();
				if (areaID == null ){
					areaID = 0L;
				}
				
				benefitID = f.getBenefitID();
				if (benefitID == null ){
					benefitID = 0L;
				}
				
				locID = f.getLocID();
				if (locID == null ){
					locID = 0L;
				}
				
				userEmail = f.getSubscribeBY();
				Subject = "";
				MessageBody = "";
				if( custID > 0 ){	
					Customer custItem = ofy2.get(Customer.class, custID);
					custName = custItem.getCustName();						
					if ( custName != null && !custName.equals("") ){
						found = false;
						if ( custName.equalsIgnoreCase("All Customers") || custName.equalsIgnoreCase("Not Customer Specific") ){
							found = true;
						}else if ( custName.equalsIgnoreCase(ff.getCustomer()) ){
							found = true;
						}				
						if( found ){
							Subject = "[Ops Notification] New Solution submitted at OpsCentral Tool for Customer " + custName ;
							MessageBody = "Please find the details of the new solution been sumitted at the ops Central tool for customer: " + custName + ". Click the below link to access the solution details.";
							MessageBody = MessageBody + " - " + siteURL + "/modules/default/display-solution.jsp?sol_id=" + ff.getSolID();
							sendEmail(userEmail, ff.getSubmittedBY() ,Subject, MessageBody, resp);
							out.println("Mail Sent: " + MessageBody + "<br />");
						}
					}
				} //custID > 0
				
				if( areaID > 0 ){	
					Area areaItem = ofy.get(Area.class, areaID);
					areaName = areaItem.getAreaName();
					if ( areaName != null && !areaName.equals("") ){
						if ( areaName.equalsIgnoreCase(ff.getProcessArea()) ){
							Subject = "[Ops Notification] New Solution submitted at OpsCentral Tool for Process Area " + areaName ;
							MessageBody = "Please find the details of the new solution been sumitted at the ops Central tool for Process Area: " + areaName + ". Click the below link to access the solution details.";
							MessageBody = MessageBody + " - " + siteURL + "/modules/default/display-solution.jsp?sol_id=" + ff.getSolID();
							sendEmail(userEmail, ff.getSubmittedBY() ,Subject, MessageBody, resp);
							out.println("Mail Sent: " + MessageBody + "<br />");
						}						
					}
				}
				
				if( benefitID > 0 ){	
					Benefit benefitItem = ofy.get(Benefit.class, benefitID);
					benefitName = benefitItem.getBenefitName();
					if ( benefitName != null && !benefitName.equals("") ){
						if ( benefitName.equalsIgnoreCase(ff.getAchievedTypeDesc()) || benefitName.equalsIgnoreCase("Hard Savings") || benefitName.equalsIgnoreCase("Cost Avoidance") || benefitName.equalsIgnoreCase("Opportunity Costs") ){
							Subject = "[Ops Notification] New Solution submitted at OpsCentral Tool for Benefit " + benefitName ;
							MessageBody = "Please find the details of the new solution been sumitted at the ops Central tool for Benefit: " + benefitName + ". Click the below link to access the solution details.";
							MessageBody = MessageBody + " - " + siteURL + "/modules/default/display-solution.jsp?sol_id=" + ff.getSolID();
							sendEmail(userEmail, ff.getSubmittedBY() ,Subject, MessageBody, resp);
							out.println("Mail Sent: " + MessageBody + "<br />");
						}						
					}
				}
				
				if( locID > 0 ){	
					Location locItem = ofy.get(Location.class, locID);
					locName = locItem.getLocationName();
					if ( locName != null && !locName.equals("") ){
						if ( locName.equalsIgnoreCase(ff.getLocation()) ){
							Subject = "[Ops Notification] New Solution submitted at OpsCentral Tool for Process Area " + locName ;
							MessageBody = "Please find the details of the new solution been sumitted at the ops Central tool for Location: " + locName + ". Click the below link to access the solution details.";
							MessageBody = MessageBody + " - " + siteURL + "/modules/default/display-solution.jsp?sol_id=" + ff.getSolID();
							sendEmail(userEmail, ff.getSubmittedBY() ,Subject, MessageBody, resp);
							out.println("Mail Sent: " + MessageBody + "<br />");
						}						
					}
				}
				
			}
		}				
		*/
		
		}catch(Exception ee){out.println("ERROR: " + ee.getMessage() + "<br />"); }
		
	}
	
	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
	throws ServletException, IOException {
			doGet(req, resp);
	}	
	
	
	
	public void sendEmail(String To, String From, String Subject, String sMessage, HttpServletResponse resp) throws IOException{
		Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);
        PrintWriter out = resp.getWriter();
        
		try {
			
            Message msg = new MimeMessage(session);
            
            msg.setFrom(new InternetAddress(From, "Ops Central Admin"));
            msg.addRecipient(Message.RecipientType.TO,
                             new InternetAddress(To, UsersInfo.getFullName(To) ));
            msg.setSubject(Subject);
            //msg.setText(sMessage);
            msg.setContent(sMessage, "text/html");
            Transport.send(msg);

        } catch (Exception e) {
        	out.println( e.getMessage() );
        } 	
		
	}
}


/*

		try {

				out.println("Started Processing <br/ >");
				_logger.info("Cron Job has been executed");
				Objectify ofy = ObjectifyService.begin();
				Query<SolutionSubscription> q = ofy.query(SolutionSubscription.class);
				
				// Get today as a Calendar  
				Calendar today = Calendar.getInstance();  
				// Subtract 1 day  
				today.add(Calendar.DATE, -1);  
				// get the yesterday date  
				java.util.Date yesterday = new java.util.Date (today.getTimeInMillis());
				java.util.Date todayDate = new java.util.Date();
				out.println("*Yesterday day: " + yesterday + "<br />");
				out.println("*Today Date: " + todayDate + "<br />");
				String siteURL = System.getProperty("SITE_URL");
				
				SimpleDateFormat dt = new SimpleDateFormat("MM/dd/yyyy");
				String fromDt = dt.format(yesterday);
				String toDt = dt.format(todayDate);
				
				java.util.Date ydate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.ENGLISH).parse(fromDt + " 00:00:01");
				java.util.Date tdate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.ENGLISH).parse(toDt + " 00:00:01");
				out.println("Ydate: " + ydate + "<br />");
				out.println("*Tdate: " + tdate + "<br />");
				
				
				
				SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd");
				String dtyesterday = dt.format(yesterday);
				dtyesterday = dtyesterday + " 00:00:00";
								
				//java.sql.Date yesterday = new java.sql.Date(today.getTimeInMillis()); 
								
				//Date dtyesterday = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.ENGLISH).parse(yesterday);			
				
				//String dtyesterday = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.ENGLISH).format(yesterday);
				String dttodayDate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.ENGLISH).format(todayDate);
				
				//SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd");
				//String dtyesterday = fdate.format(yesterday);
				//String dttodayDate = fdate.format(todayDate);
				
				out.println("Yesterday Date: " + dtyesterday + "<br />");
				out.println("Today Date: " + dttodayDate + "<br />");
				
				
				Long custID;
				Long areaID;
				Long benefitID;
				Long locID;
				String userEmail = "";
				String Subject =  "";
				String MessageBody = "";
				
				String custName = "";
				String areaName = "";
				String benefitName = "";
				String locName = "";
				
				
				for (SolutionSubscription f : q.fetch()) {

					custID = areaID = benefitID = locID = 0L;
					
					custID = f.getCustID();
					if (custID == null ){
						custID = 0L;
					}

					areaID = f.getAreaID();
					if (areaID == null ){
						areaID = 0L;
					}
					
					benefitID = f.getBenefitID();
					if (benefitID == null ){
						benefitID = 0L;
					}
					
					locID = f.getLocID();
					if (locID == null ){
						locID = 0L;
					}
					
					userEmail = f.getSubscribeBY();
					Subject = "";
					MessageBody = "";
					out.println("Processing Subscription: " + f.getSubscID() + "<br />");
				
					//Check for Customer and send email
					if( custID > 0 ){	
						Customer custItem = ofy.get(Customer.class, custID);
						custName = custItem.getCustName();						
						if ( custName != null && !custName.equals("") ){
							//Query<SolutionSubmission> solItem = ofy.query(SolutionSubmission.class).filter("submittedON >=", ydate);
							out.println("**************Start" + "<br />");
							java.util.Date fdate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH).parse("2012-10-15" + " 00:00:01");
							SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
							String DisplayDate =  dt1.format(todayDate);
							
							java.util.Date xfdate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.ENGLISH).parse("10/15/2012" + " 00:00:01");							
							//Query<SolutionSubmission> solItem = ofy.query(SolutionSubmission.class).filter("Status", "Shared").filter("submittedON <", xfdate);
							Query<SolutionSubmission> solItem = ofy.query(SolutionSubmission.class).filter("Status", "Shared").filter("modifiedON <=", todayDate);
							
							//solItem.filter("submittedON <", tdate);
							out.println("**************End" + "<br />");
							out.println("Search Date: " + DisplayDate + " = Today: " + fdate + " <br />");
							if ( solItem!=null && solItem.countAll() > 0 ){
								out.println("1.Breakpoint" + solItem.countAll() + "<br />");
								if ( custName.equalsIgnoreCase("All Customers") || custName.equalsIgnoreCase("Not Customer Specific") ){
									//ALL CUSTOMER NO FILTER.	
								}else{
									//FILTER FOR SPECIFIC CUSTOMER
									solItem.filter("Customer", custName);
								}
								out.println("2.Breakpoint" + "<br />");
								for (SolutionSubmission ff : solItem.fetch()) {
									
									Subject = "[Ops Notification] New Solution submitted at OpsCentral Tool for Customer " + custName ;
									MessageBody = "Please find the details of the new solution been sumitted at the ops Central tool for customer: " + custName + ". Click the below link to access the solution details.";
									MessageBody = MessageBody + " - " + siteURL + "/modules/default/display-solution.jsp?sol_id=" + ff.getSolID();
									sendEmail(userEmail,"opscentral@celestica.com",Subject, MessageBody);
									out.println("Mail Sent: " + MessageBody + "<br />");
								}				
								
							} //COUNT ALL
							out.println("3.Breakpoint" + "<br />");
						} //CUSTOMER NAME						
					} //CUSTID
					
					
					//Check for Process Area and send email
					if( areaID > 0 ){	
						Area areaItem = ofy.get(Area.class, areaID);
						areaName = areaItem.getAreaName();
						if ( areaName != null && !areaName.equals("") ){
							//Query<SolutionSubmission> solItem = ofy.query(SolutionSubmission.class).filter("submittedON >=", ydate);
							Query<SolutionSubmission> solItem = ofy.query(SolutionSubmission.class);
							solItem.filter("submittedON >=", ydate);

							out.println("Search Date: " + yesterday + " - Today: " + todayDate + " <br />");

							if ( solItem.countAll() > 0 ){
								//FILTER FOR SPECIFIC AREA
								solItem.filter("processArea", areaName);
								for (SolutionSubmission ff : solItem.fetch()) {
									Subject = "[Ops Notification] New Solution submitted at OpsCentral Tool for Process Area " + areaName ;
									MessageBody = "Please find the details of the new solution been sumitted at the ops Central tool for Process Area: " + areaName + ". Click the below link to access the solution details.";
									MessageBody = MessageBody + " - " + siteURL + "/modules/default/display-solution.jsp?sol_id=" + ff.getSolID();
									sendEmail(userEmail,"opscentral@celestica.com",Subject, MessageBody);
									out.println("Mail Sent: " + MessageBody + "<br />");
								}
							} //COUNT ALL							
						} //AREA NAME						
					} //AREAID

					//Check for Benefits and send email
					if( benefitID > 0 ){	
						Benefit benefitItem = ofy.get(Benefit.class, benefitID);
						benefitName = benefitItem.getBenefitName();
						if ( benefitName != null && !benefitName.equals("") ){
							//Query<SolutionSubmission> solItem = ofy.query(SolutionSubmission.class).filter("submittedON >=", ydate);
							Query<SolutionSubmission> solItem = ofy.query(SolutionSubmission.class);
							solItem.filter("submittedON >=", ydate);

							out.println("Search Date: " + yesterday + " - Today: " + todayDate + " <br />");

							if ( solItem.countAll() > 0 ){
								
								//FILTER FOR SPECIFIC BENEFIT						
								
								if( benefitName.equalsIgnoreCase("Hard Savings")){ 
									solItem.filter("hasHardSavings", true);
								}else if( benefitName.equalsIgnoreCase("Cost Avoidance")){
									solItem.filter("hasCostAvoidance", true);
								}else if( benefitName.equalsIgnoreCase("Opportunity Costs")){
									solItem.filter("hasOppurtunityCost", true);	
								}else{
									solItem.filter("achievedTypeDesc", benefitName);
								}
								
								for (SolutionSubmission ff : solItem.fetch()) {
									Subject = "[Ops Notification] New Solution submitted at OpsCentral Tool for Process Area " + benefitName ;
									MessageBody = "Please find the details of the new solution been sumitted at the ops Central tool for Process Area: " + areaName + ". Click the below link to access the solution details.";
									MessageBody = MessageBody + " - " + siteURL + "/modules/default/display-solution.jsp?sol_id=" + ff.getSolID();
									sendEmail(userEmail,"opscentral@celestica.com",Subject, MessageBody);
									out.println("Mail Sent: " + MessageBody + "<br />");
								}
							} //COUNT ALL							
						} //BENEFIT NAME						
					} //benefitID

					//Check for Location and send email
					if( locID > 0 ){	
						Location locItem = ofy.get(Location.class, locID);
						locName = locItem.getLocationName();
						if ( locName != null && !locName.equals("") ){
							//Query<SolutionSubmission> solItem = ofy.query(SolutionSubmission.class).filter("submittedON >=", ydate);
							Query<SolutionSubmission> solItem = ofy.query(SolutionSubmission.class);
							solItem.filter("submittedON >=", ydate);

							out.println("Search Date: " + yesterday + " - Today: " + todayDate + " <br />");

							if ( solItem.countAll() > 0 ){
								
								//FILTER FOR SPECIFIC LOCATION						
								solItem.filter("Location", locName);								
								
								for (SolutionSubmission ff : solItem.fetch()) {
									Subject = "[Ops Notification] New Solution submitted at OpsCentral Tool for Process Area " + locName ;
									MessageBody = "Please find the details of the new solution been sumitted at the ops Central tool for Process Area: " + areaName + ". Click the below link to access the solution details.";
									MessageBody = MessageBody + " - " + siteURL + "/modules/default/display-solution.jsp?sol_id=" + ff.getSolID();
									sendEmail(userEmail,"opscentral@celestica.com",Subject, MessageBody);
									out.println("Mail Sent: " + MessageBody + "<br />");
								}
							} //COUNT ALL							
						} //LOCATION NAME						
					} //locID
					
					
				}
				
				out.println("End of Processing <br/ >"); 
			}
			
		catch (Exception ex) {
				//Log any exceptions in your Cron Job
			out.println("Exception <br/ >" + ex.getMessage());
		}


*/